package com.vipsoft.locker.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import com.vipsoft.base.core.ApiResult;
import com.vipsoft.base.util.PojoUtil;
import com.vipsoft.base.entity.locker.vo.UploadFileModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Date;

/**
 * 文件上传
 */
@RestController
@RequestMapping("/upload")
public class UploadController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${vipsoft.item-images-path}")
    String savePath;

    /**
     * 获取已上传文件大小
     *
     * @param request
     * @param param
     * @return
     */
    @PostMapping("/getFileLength")
    public ApiResult getFileLength(HttpServletRequest request, @RequestBody UploadFileModel param) {
        //判断入参是否为空
        ApiResult result = new ApiResult();
        try {
            String fileName = "";
            if (param != null) {
                fileName = param.getFileName();
            }
            if (StrUtil.isEmpty(fileName)) {
                //实体没有就从Header 里面取
                fileName = request.getHeader("FileName");
            }
            if (StrUtil.isEmpty(fileName)) {
                result.setCode(6001);
                result.setMessage("FileName 文件名不能为空");
                result.setData(0);
                return result;
            }
            //设置文件存放路径
            //string dir = HttpContext.Current.Server.MapPath(SavePath);
            fileName = savePath + "\\" + fileName;
            String msg = "";
            if (FileUtil.exist(fileName)) {
                File file = new File(fileName);
                result.setData(file.length());
                msg = StrUtil.indexedFormat("FileName => {0} Length => {1}", fileName, file.length());
            } else {
                result.setData(0);
                msg = StrUtil.indexedFormat("文件不存在 FileName => {0} Length => 0", fileName);
            }
            result.setMessage("获取成功！");
            result.setCode(0);
            msg = StrUtil.indexedFormat("文件不存在 FileName => {0} Length => 0", fileName);
            logger.info("获取文件长度 => {}", msg);

        } catch (Exception ex) {
            logger.error(PojoUtil.pojoToJson(param));
            logger.error(ex.getMessage(), ex);
            result.setCode(6001);
            result.setMessage(ex.getMessage());
        }
        return result;
    }

    /**
     * 上传文件
     *
     * @param request
     * @return
     */
    @PostMapping("/uploadFile")
    public ApiResult uploadFile(HttpServletRequest request, @RequestParam(value = "file") MultipartFile file) {
        //判断入参是否为空
        ApiResult result = new ApiResult();
        String fileName = "";
        RandomAccessFile writeFile = null;
        try {
            String memberId = request.getHeader("memberId");
            fileName = request.getParameter("fileName");
            long offset = 0;
            String offsetStr = request.getHeader("offset");
            if (StrUtil.isEmpty(offsetStr)) {
                offsetStr = request.getParameter("offset");
            }
            if (StrUtil.isNotEmpty(offsetStr)) {
                offset = Long.valueOf(offsetStr);
            }
            String originalFilename = file.getOriginalFilename();
            if (StrUtil.isEmpty(fileName)) {
                fileName = DatePattern.PURE_DATETIME_MS_FORMAT.format(new Date()) + "." + FileUtil.extName(originalFilename);
            }
            if (StrUtil.isNotEmpty(memberId)) {
                fileName = memberId + "/" + fileName;//加上用户ID，便于区分
            }
            File dir = new File(savePath + "/" + memberId);
            //如果不存在文件夹，就创建文件夹
            if (!dir.exists()) {
                logger.info("不存在，创建目录：{}/{}", savePath, memberId);
                boolean flag = dir.mkdirs();
                logger.info("{}", flag ? "创建成功" : "创建失败");
            }
            String fullFileName = savePath + "/" + fileName;
            writeFile = new RandomAccessFile(fullFileName, "rw");
            writeFile.seek(offset);
            long upLoadLength = file.getSize();
            writeFile.write(file.getBytes());
            result.setCode(1);
            result.setMessage("上传成功!");
            result.setData("/" + fileName);
            logger.info("上传文件 {} Offset => {} File.ContentLength => {} => {}", fileName, offset, upLoadLength, fullFileName);
        } catch (IOException e) {
            result.setCode(6003);
            result.setMessage(e.getMessage());
            result.setData(false);
            logger.error(e.getMessage() + " => " + fileName, e);
        } finally {
            IoUtil.close(writeFile);
        }
        return result;
    }

}
